<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<title>教师端|成绩登记</title>
<link rel="icon" href="${ctx}/static/favicon.ico" type="image/ico">
<link href="${ctx}/static/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="${ctx}/static/bootstrap/css/materialdesignicons.min.css" rel="stylesheet">
<link href="${ctx}/static/bootstrap/css/animate.css" rel="stylesheet">
<link href="${ctx}/static/bootstrap/css/style.min.css" rel="stylesheet">
<link href="${ctx}/static/bootstrap/js/bootstrap-table/bootstrap-table.min.css" rel="stylesheet">
<link href="${ctx}/static/bootstrap/js/x-editable/1.5.1/bootstrap3-editable/css/bootstrap-editable.min.css" rel="stylesheet">
<!--对话框-->
<link rel="stylesheet" href="${ctx}/static/bootstrap/js/jconfirm/jquery-confirm.min.css">
<link href="${ctx}/static/bootstrap/css/style.min.css" rel="stylesheet">
<!--通知消息-->
<link href="${ctx}/static/bootstrap/css/materialdesignicons.min.css" rel="stylesheet">
<link href="${ctx}/static/bootstrap/css/animate.css" rel="stylesheet">
<style type="text/css">
	label.error{color:red;}	
</style>
</head>
<body>
	<div class="container-fluid p-t-15">
		<div class="row">
			<div class="col-lg-12">
				<div class="card">
					<div class="card-header">
						<h4>成绩列表</h4>
					</div>
					<div class="card-body" style="margin-bottom:0px;padding-bottom:0px;">
						<form class="form-inline" id="form-grade-query">
							<div class="form-group">
								<label for="gradeName" class="control-label">学号：</label> 
								<input class="form-control" type="text" id="stuId" name="stuId" style="width:100px;">
							</div>
							<div class="form-group">
								<label for="gradeName" class="control-label">课程编号：</label> 
								<input class="form-control" type="text" id="curId" name="curId" style="width:100px;">
							</div>
							<div class="form-group">
								<label for="gradeName" class="control-label">学年学期：</label> 
								<input class="form-control" type="text" id="semester" name="semester" style="width:100px;">
							</div>
							<div class="form-group">
								<button class="btn btn-success" id="btnQuery" type="button">查询</button>
								<button class="btn btn-danger" id="btnReset" type="button">重置</button>
							</div>
						</form>
					</div>
					<div class="card-body">
						<div id="toolbar" class="toolbar-btn-action">
							<button id="btn_add" type="button" class="btn btn-primary m-r-5" data-toggle="modal" data-target="#addModal" data-whatever="@mdo">
								<span class="mdi mdi-plus" aria-hidden="true"></span>新增
							</button>
							<button id="btn_delete" type="button" class="btn btn-danger" onclick="deleteByIds()">
								<span class="mdi mdi-window-close" aria-hidden="true"></span>删除
							</button>
						</div>
						<table id="myTable"></table>
						<!-- 新增模态框开始 -->
						<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
							<div class="modal-dialog" role="document">
								<div class="modal-content">
									<div class="modal-header">
										<button type="button" class="close" data-dismiss="modal" aria-label="Close">
											<span aria-hidden="true">&times;</span>
										</button>
										<h4 class="modal-title" id="exampleModalLabel">新增成绩</h4>
									</div>
									<div class="modal-body">
										<form id="form-grade-add">
											<div class="form-group">
												<label for="gradeName" class="control-label">学生：</label>												
												<select class="form-control" id="stuId" name="stuId">
													<option value="">---请选择学生---</option>
													<c:forEach items="${students}" var="obj">
														<option value="${obj.id}">${obj.id}--------${obj.studentName}</option>
													</c:forEach>
												</select>
											</div>
											<div class="form-group">
												<label for="gradeName" class="control-label">课程：</label>												
												<select class="form-control" id="curId" name="curId">
													<option value="">---请选择课程---</option>
													<c:forEach items="${curriculums}" var="item">
														<option value="${item.id}">${item.id}--------${item.curName}</option>
													</c:forEach>
												</select>
											</div>
											<div class="form-group">
												<label for="gradeName" class="control-label">学年学期：</label> 
												<input class="form-control" type="text" id="semester" name="semester" value="${systeminfo.semester}">
											</div>
											<div class="form-group">
												<label for="gradeName" class="control-label">成绩：</label> 
												<input class="form-control" type="text" id="grade" name="grade">
											</div>
										</form>
									</div>
									<div class="modal-footer">
										<button type="submit" id="btnSubmit" onclick="add()" class="btn btn-primary">保存</button>
										<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
									</div>
								</div>
							</div>
						</div>
						<!-- 新增模态框结束 -->
						<!-- 编辑模态框开始 -->
						<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
							<div class="modal-dialog" role="document">
								<div class="modal-content">
									<div class="modal-header">
										<button type="button" class="close" data-dismiss="modal" aria-label="Close">
											<span aria-hidden="true">&times;</span>
										</button>
										<h4 class="modal-title" id="exampleModalLabel">修改成绩</h4>
									</div>
									<div class="modal-body">
										<form id="form-grade-edit">
											<input type="hidden" class="form-control" id="index" name="index">
											<input type="hidden" class="form-control" id="id" name="id">
											<div class="form-group">
												<label for="gradeName" class="control-label">学号：</label> 
												<input class="form-control" type="text" id="stuId" name="stuId" readonly="readonly">
											</div>
											<div class="form-group">
												<label for="gradeName" class="control-label">课程编号：</label> 
												<input class="form-control" type="text" id="curId" name="curId" readonly="readonly">
											</div>
											<div class="form-group">
												<label for="gradeName" class="control-label">学年学期：</label> 
												<input class="form-control" type="text" id="semester" name="semester" readonly="readonly" >
											</div>
											<div class="form-group">
												<label for="gradeName" class="control-label">成绩：</label> 
												<input class="form-control" type="text" id="grade" name="grade">
											</div>
										</form>
									</div>
									<div class="modal-footer">
										<button type="submit" id="btnSubmit" onclick="edit()" class="btn btn-primary">保存</button>
										<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
									</div>
								</div>
							</div>
						</div>
						<!-- 编辑模态框结束 -->
					</div>
				</div>
			</div>
		</div>
	</div>

	<script type="text/javascript" src="${ctx}/static/bootstrap/js/jquery.min.js"></script>
	<script type="text/javascript" src="${ctx}/static/bootstrap/js/bootstrap.min.js"></script>
	<script type="text/javascript" src="${ctx}/static/bootstrap/js/perfect-scrollbar.min.js"></script>
	<script type="text/javascript" src="${ctx}/static/bootstrap/js/bootstrap-table/bootstrap-table.min.js"></script>
	<script type="text/javascript" src="${ctx}/static/bootstrap/js/bootstrap-table/bootstrap-table-zh-CN.min.js"></script>
	<!--表单验证插件-->
	<script type="text/javascript" src="${ctx}/static/bootstrap/js/jquery-validation-1.19.3/jquery.validate.js"></script>
	<script type="text/javascript" src="${ctx}/static/bootstrap/js/jquery-validation-1.19.3/jquery.validate.extend.js"></script>
	<script type="text/javascript" src="${ctx}/static/bootstrap/js/jquery-validation-1.19.3/additional-methods.js"></script>
	<script type="text/javascript" src="${ctx}/static/bootstrap/js/jquery-validation-1.19.3/messages_zh.js"></script>
	<!--行内编辑插件-->
	<script type="text/javascript" src="${ctx}/static/bootstrap/js/x-editable/1.5.1/bootstrap3-editable/js/bootstrap-editable.min.js"></script>
	<script type="text/javascript" src="${ctx}/static/bootstrap/js/bootstrap-table/extensions/editable/bootstrap-table-editable.min.js"></script>
	<!--对话框-->
	<script src="${ctx}/static/bootstrap/js/jconfirm/jquery-confirm.min.js"></script>
	<!--消息提示-->
	<script src="${ctx}/static/bootstrap/js/bootstrap-notify.min.js"></script>
	<script type="text/javascript" src="${ctx}/static/bootstrap/js/lightyear.js"></script>
	<script type="text/javascript" src="${ctx}/static/bootstrap/js/main.min.js"></script>
	
	
	<script type="text/javascript">
		//获取上下文路径
		function getContextPath(){
		    var pathName = document.location.pathname;
		    var index = pathName.substr(1).indexOf("/");
		    var result = pathName.substr(0,index+1);
		    return result;
		}
	
		var ctx = getContextPath();
		
		var addUrl = "${ctx}/grade/add";
		var deleteUrl = "${ctx}/grade/delete/";
		var editUrl = "${ctx}/grade/edit";
		var listUrl = "${ctx}/grade/map";
		var addForm = $("#form-grade-add");
		var editForm = $("#form-grade-edit");
		var queryForm = $("#form-grade-query");
		
		
		//数据验证：服务端验证（JSR303，Hibernate validator ）+和客户端验证（jquery.validate.js）		
		$(function(){
			var options = {
				onkeyup:function(element,event){
					var value = $.trim(this.elementValue(element));
					$(element).val(value);
				},
				rules:{//定义验证的规则
					stuId:{
						required:true
					},	
					curId:{
						required:true
					},	
					semester:{
						required:true
					},	
					grade:{
						required:true,
						range:[0,100]
					}				
				},
				messages: {//定义规则对应的提示信息
					stuId:{
						required:"学生编号不能为空"
					},	
					curId:{
						required:"课程编号不能为空"
					},	
					semester:{
						required:"学年学期不能为空"
					},	
					grade:{
						required: "成绩不能为空",
						range:"成绩范围(0~100)"
					}
				}
			};
			var validate1 = addForm.validate(options);
			var validate2 = editForm.validate(options);
		})
		
		//查询
		$("#btnQuery").click(function(){
			$("#myTable").bootstrapTable('refresh');
		})
		
		//重置
		$("#btnReset").click(function(){
			queryForm[0].reset();
			$("#myTable").bootstrapTable('refresh');
		})
		
		//新增
		function add(){
			if(addForm.valid()){
				$.post(addUrl,addForm.serialize(),function(data,status){
					//通知消息
					if(data.code == 0){	
						//关闭模态框
						$("#addModal").modal('hide');
						//清空表单
						addForm[0].reset();
						//添加显示新增的数据
						$("#myTable").bootstrapTable('prepend',data.obj);	
						lightyear.notify(data.msg, 'success', 1000, 'mdi mdi-emoticon-happy', 'top', 'right');
					}else{
						lightyear.notify(data.msg, 'danger', 1000, 'mdi mdi-emoticon-happy', 'top', 'right');
					}				
			    });
			}
		}
		
		//打开modal，获取数据
		function get(id, index){
			//获取数据，方式：获取页面上的数据
			var rowData = $("#myTable").bootstrapTable('getRowByUniqueId', id);
			//将数据填充到编辑表单
			$("#editModal").find("#index").val(index);
			$("#editModal").find("#id").val(rowData.id);
			$("#editModal").find("#stuId").val(rowData.stuId);
			$("#editModal").find("#curId").val(rowData.curId);
			$("#editModal").find("#semester").val(rowData.semester);
			$("#editModal").find("#grade").val(rowData.grade);
			//显示Model（表单）
			$("#editModal").modal('show');
		}
		
		//编辑
		function edit(id)
		{
			if(editForm.valid()){
				var index = $("#editModal").find("#index").val();
				$.post(editUrl,editForm.serialize(),function(data,status){
					//通知消息
					if(data.code == 0){	
						var row = data.obj;
						//关闭模态框
						$("#editModal").modal('hide');
						//清空表单
						editForm[0].reset();
						//添加显示修改后的数据
						$("#myTable").bootstrapTable('updateRow',{index:index,row:row});	
						lightyear.notify(data.msg, 'success', 1000, 'mdi mdi-emoticon-happy', 'top', 'right');
					}else{
						lightyear.notify(data.msg, 'danger', 1000, 'mdi mdi-emoticon-sad', 'top', 'right');
					}				
			    });
			}
		}
		
		//单选删除
		function deleteById(id){
			var idsArr = new Array();
			/* alert(id); */
			idsArr[0] = id;
			deleteByIdsArr(idsArr);
		}
		
		//多选删除
		function deleteByIds(){
			//获取bootstraptable中被选择的行
			var getSelectRows = $('#myTable').bootstrapTable('getSelections'); //结果是数组
			if(getSelectRows.length == 0){
				alert("请至少选择一条记录！");
				return;
			}
			//将选中的记录Id组成数组形式
			var idsArr = new Array();
			for(var i=0;i<getSelectRows.length;i++){
				idsArr[i] = getSelectRows[i].id;
			}
			/* alert(idsArr); */
			deleteByIdsArr(idsArr);
		}
		
		//根据id数组删除指定记录
		function deleteByIdsArr(idsArr)//idsArr[i]->1,2,3,4,5
		{
			var ids = idsArr.join(",");//1,2,3,4,5
			$.alert({
		        title: '删除确认',
		        content: '确定要删除吗？',
				buttons: {
					confirm: {
						text: '确认',
						btnClass: 'btn-primary',
						action: function(){//${ctx}/grade/delete/1,2,3,4,5
							$.get(deleteUrl + ids,function(result) {
								if(result.code == 0){
									//刷新表格
									//在表格中根据id删除1行
									//$('#myTable').bootstrapTable('removeByUniqueId',id);
									//在表格中根据id删除多行
									$('#myTable').bootstrapTable('remove',{field:'id', values:idsArr});
									//如果当前页面所有数据被删除，则出现空白页面
									//getData方法：获取当前页的数据数量，返回的一个数组
									var list = $("#myTable").bootstrapTable('getData');
									//console.log("after delete list.length=" + list.length);			
									if(list.length == 0){
										$("#myTable").bootstrapTable('refreshOptions',{pageNumber:1});
									}
									//通知消息	
									lightyear.notify(result.msg, 'success', 1000, 'mdi mdi-emoticon-happy', 'top', 'right');
								}else{
									lightyear.notify(result.msg, 'danger', 1000, 'mdi mdi-emoticon-sad', 'top', 'right');
								}
							});
						}
					},
					cancel: {
						text: '取消',
						action: function () {		                    
						}
					}
				}
		    });
		}
		
		
		$("#myTable").bootstrapTable({
			classes: 'table table-bordered table-hover table-striped', //指定表格样式
			url: listUrl, //获取远程(后台)数据的url
		    method: 'get',  //请求方式 get,post
		    dataType : 'json',        //数据形式：json，若是跨域，则使用jsonp，因为本示例中是跨域的调用,所以涉及到ajax都采用jsonp,
			uniqueId: 'id',
		    idField: 'id',    // 每行的唯一标识字段 
			toolbar: '#toolbar', //指定工具栏
			//clickToSelect: true,     // 是否启用点击选中行
			showColumns: true, //是否显示所有列
			showToggle: true,  //是否显示详细视图和列表视图的切换按钮(clickToSelect同时设置为true时点击会报错)		  
			showRefresh: true, //是否显示刷新按钮
			search: false,      //是否启用搜索，客户端搜索
			pagination: true,  //是否启用分页
			sortOrder: 'asc',  //排序方式：asc-升序，desc-降序，按照idField
			queryParams: function(params) {
				var pageSize = params.limit;
				var offset = params.offset;
				var pageNumber = (offset / pageSize) + 1
				var sort = params.sort;
				var sortOrder = params.order;
				var paramsNew = queryForm.serialize().concat("&pageNumber="+pageNumber).concat("&offset="+offset).concat("&pageSize="+pageSize).concat("&sort="+sort).concat("&sortOrder="+sortOrder);
	            return  paramsNew;
		    },     
			sidePagination: "server",            // 分页方式：client客户端分页，server服务端分页
		    pageNumber: 1,                       // 初始化加载第一页，默认第一页
		    pageSize: 10,                        // 每页的记录行数
		    pageList: [10, 25, 50, 100],         // 可供选择的每页的行数
			//showExport: true,        // 是否显示导出按钮, 导出功能需要导出插件支持(tableexport.min.js)
		    //exportDataType: "basic", // 导出数据类型, 'basic':当前页, 'all':所有数据, 'selected':选中的数据	
			 columns: [{
				checkbox: true //是否显示复选框
			},{
				field: 'id',
				title: '成绩编号'	,
				//visible: false,  //隐藏
				sortable: true	 //是否排序			
			},{
				field: 'stuId',
				title: '学号'	
			},{
				field: 'student.studentName',
				title: '学生姓名'	
			},{
				field: 'curId',
				title: '课程标号'	
			},{
				field: 'curriculum.curName',
				title: '课程名称'	
			},{
				field: 'semester',
				title: '学年学期'	
			},{
				field: 'grade',
				title: '成绩'	
			},{
				field: 'operate',
				title: '操作',
				formatter: btnGroup, //btnGroup是一个函数的名字，该函数定义当前列如何显示
				events: {//事件
		            'click .edit-btn': function (event, value, row, index) {
		                get(row.id, index);
		            },
		            'click .del-btn': function (event, value, row, index) {
		            	deleteById(row.id);
		            }
		        }		
			}]
		});
		
		// 操作按钮
		function btnGroup(){
			var html =
		        '<a href="#!" class="btn btn-xs btn-warning m-r-5 edit-btn" title="编辑" data-toggle="tooltip">编辑</a>' +
		        '<a href="#!" class="btn btn-xs btn-danger del-btn" title="删除" data-toggle="tooltip">删除</a>';
		    return html;
		}   
	</script>
</body>
</html>